package com.sunelec.utils;

/**
 * @Author: 郑明利
 * @Description:
 * @Date: Create in 19:46 2018/04/17
 * @Modified By:
 */

import com.sunelec.pojo.Users;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.*;

public class SessionListener implements HttpSessionListener{

    private static Logger log = Logger.getLogger(SessionListener.class);

    @Override
    public void sessionCreated(HttpSessionEvent event) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId = session.getId();
        //在session销毁的时候,把loginUserMap中保存的键值对清除
        Users user = (Users) session.getAttribute("now_user");
        if (user != null) {
            Map<String, String> loginUserMap = (Map<String, String>) event.getSession().getServletContext().getAttribute("loginUserMap");
            if(loginUserMap.get(user.getUsersname()).equals(sessionId)){
                log.info("clean user from application : " + user.getUsersname());
                loginUserMap.remove(user.getUsersname());
                event.getSession().getServletContext().setAttribute("loginUserMap", loginUserMap);
            }
        }

    }
}